package com.yinxing.netty.handler;

import com.yinxing.netty.utils.NettyUtils;
import com.yinxing.netty.utils.ServerUtils;
import io.netty.channel.*;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler.HandshakeComplete;
import lombok.extern.slf4j.Slf4j;

/**
 * ws事件处理
 */
@Slf4j
@ChannelHandler.Sharable
public class WebSocketEventHandler extends ChannelInboundHandlerAdapter {

    public static final WebSocketEventHandler INSTANCE = new WebSocketEventHandler();

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        //WebSocket握手成功事件
        if (evt instanceof HandshakeComplete) {
            final Channel channel = ctx.channel();
            final String remoteHostPort = NettyUtils.getRemoteHostPort(channel);

            //握手路径例如：/websocket/userId=749058260664978888
            HandshakeComplete handshakeComplete = (HandshakeComplete) evt;
            log.info("ws握手成功:{{}} - http握手地址:{{}}", remoteHostPort, handshakeComplete.requestUri());

            //获取用户ID
            Long sysUserId = getUserId(handshakeComplete.requestUri());

            //channel绑定用户信息，然后加入容器.
            ServerUtils.channelLogin(sysUserId, channel);

            //如果客户端数量多,则心跳任务应由客户端发起,后台系统连接数量不多无所谓.
            ServerUtils.startHeartbeat(channel);
        }
        super.userEventTriggered(ctx, evt);
    }

    private Long getUserId(String requestUri) {
        int userIdIndex = requestUri.indexOf("=") + 1;
        return Long.valueOf(requestUri.substring(userIdIndex));
    }
}
